<?php

namespace app\miniprograms\controller;

use controller\BasicAdmin;
use service\DataService;
use service\NodeService;
use service\ToolsService;
use think\App;;
use think\Db;
use think\Exception;
use app\common\model\Enum;
use app\common\library\excel\Office;
use think\facade\Log;

// use PHPExcel_IOFactory;
// use PHPExcel;

/**
 * Class Area
 * @package app\admin\controller
 * @author liuda <1576283429@qq.com>

 * @date
 */
class Recharge extends BasicAdmin
{
	
    public $table = 'recharge_config';

    public function index(){
        $this->title = '充值列表';
        $list = Db::table('recharge_config')->select();
        $this->assign('list', $list);
        return $this->fetch();
    }


    /**
     * 表单数据默认处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {    //添加处理
            try{
                $id = $this->request->post('id');
                $recharge_amount = ($this->request->post('recharge_amount'))*100;
                $gift_amount = ($this->request->post('gift_amount'))*100;
                Db::name('recharge_config')->where('id',$id)->update(['recharge_amount'=>$recharge_amount,'gift_amount'=>$gift_amount]);
                $this->success('恭喜, 数据保存成功!', '');
            }catch (Exception $e){
                $this->error('添加数据失败，请稍后再试！');
            }
        }
    }



    /*
     * 编辑价格
     */
    public function edit()
    {
        $id = $this->request->get('id');
        $list = Db::table('recharge_config')->where(['id'=>$id])->select();
        $this->assign('list', $list);
        return $this->_form($this->table, 'form');
    }

    //充值列表
    public function report(){
        $this->title = '充值列表';
        $where = ' 1 ';
        $excel = $this->request->get('excel');
        $code = $this->request->get('code');
        $type = $this->request->get('type');
        $pay_status = $this->request->get('pay_status');
        $date = $this->request->get('date');
        
        if(is_numeric($pay_status)){
            $where .= " AND A.pay_status = $pay_status ";
        }

        if(is_numeric($type)){
            $where .= " AND A.type = $type ";
        }

        if(!empty($date)){
            list($start, $end) = explode(' - ', $date);
            $start = $start." 00:00:00";
            $end = $end." 23:59:59";
            $where .=" AND A.create_at >= '$start'  AND A.create_at <= '$end' ";
        }

        $session = $this->request->session();
        $user = $session['user'];  //$user['is_admin']  1为管理员  其余是供应商
        if( $user['is_admin'] != 1 ){
            //$where.=" AND A.user_id=".$user['id'] ;
        }

        $areas = Db::table('area')->field('id,area_name')->where('is_deleted = 0')->select(); //获取地区
        $this->assign('areas', $areas);

        $orderPaystatus = ['已付款','付款失败','未付款'];
        $this->assign('orderPaystatus', $orderPaystatus);

        $this->assign('btype', Enum::b_type_array);
        
        $list =  Db::table('charge')->alias('A')->join('user M','A.user_id = M.id','LEFT')->field('A.id,A.amount,A.pay_status,A.order_no ,A.update_at,A.gift,A.czamount,A.type,M.code')->where($where)->order('A.id desc');

        if($excel=="1"){
            $list =$list->select();
            foreach ($list as &$row){
                $tname = array_search($row["type"],Enum::b_type_array);
                if(empty($tname)){
                    $tname="";
                }
                $row["tname"] =$tname;
                $row["gift"] = $row["gift"]/100;
                $row["czamount"] =$row["czamount"]/100;
                $row["amount"] =$row["amount"]/100;
            }
            $fileName = '充值明细'.date('_YmdHis');
            $head = ['会员编号','充值金额','赠送金额','用户到账','订单状态','订单编号','订单时间'];
            $keys = ['code','czamount','gift','amount','tname','order_no','update_at'];   
            $excel = new Office();         
            $excel->outExcel($fileName, $list, $head, $keys);
        }else{
            return parent::_list($list);
        }
    }


    //充值列表
    public function backlist(){
        $this->title = '微信退款列表';
        $where = ' 1=1 ';
        $excel = $this->request->get('excel');
        $code = $this->request->get('code');
        $date = $this->request->get('date');
        
        if(!empty($date)){
            list($start, $end) = explode(' - ', $date);
            $start = $start." 00:00:00";
            $end = $end." 23:59:59";
            $where .=" AND A.update_at >= '$start'  AND A.update_at <= '$end' ";
        }

        $where.=" AND A.status = 0 " ;

        $list =  Db::table('refund')->alias('A')->join('user M','A.user_id = M.id','LEFT')->field('A.id,A.amount,A.update_at,A.create_at,A.trade_no,M.code')->where($where)->order('A.id desc');

        if($excel=="1"){
          
        }else{
            return parent::_list($list);
        }
    }

    /**
     * 退款权限
     */
    public function backmoney(){
        $this->title = '微信退款申请';
        $where = ' 1=1 ';
        $excel = $this->request->get('excel');
        $code = $this->request->get('code');
        $date = $this->request->get('date');
        
        if(!empty($date)){
            list($start, $end) = explode(' - ', $date);
            $start = $start." 00:00:00";
            $end = $end." 23:59:59";
            $where .=" AND A.create_at >= '$start'  AND A.create_at <= '$end' ";
        }

        $where.=" AND A.status = 2 " ;

        $list =  Db::table('refund')->alias('A')->join('user M','A.user_id = M.id','LEFT')->field('A.id,A.amount,A.update_at,A.create_at,A.trade_no,M.code')->where($where)->order('A.id desc');

        if($excel=="1"){
          
        }else{
            return parent::_list($list);
        }
    }

   

    public function backmoneypost(){

        $id = $this->request->post('id');

        $refund = Db::table('refund')->where("id",$id)->find();
        if(!$refund){
            return $this->renderError("refund is empty");
        }

        $user = Db::table('user')->where("id",$refund['user_id'])->find();

        $re_openid=$user['open_id'];
        $total_amount = $refund['amount'];
        $desc='e共享不愁洗衣退款到账';
        $check_name='';

        //企业付款到微信零钱，PHP接口调用方法   key=
        $APPID="wxdedae9ac8da366ad"; // 商户账号appid
        $MCHID="1523166321";  // 商户号
        $SECRECT_KEY="537f141c6f89d1cf622e2dc7f017b207"; //支付密钥签名

        $data=array(
            'mch_appid'=>$APPID,//商户账号appid
            'mchid'=> $MCHID,//商户号
            'nonce_str'=>$this->createNoncestr(),//随机字符串
            'partner_trade_no'=> date('YmdHis').rand(1000, 9999),//商户订单号
            'openid'=> $re_openid,//用户openid
            'check_name'=>'NO_CHECK',//校验用户姓名选项,
            're_user_name'=> $check_name,//收款用户姓名
            'amount'=>$total_amount,//金额
            'desc'=> $desc,//企业付款描述信息
            'spbill_create_ip'=> $this->request->ip(),//Ip地址
        );

        //生成签名算法
        $secrect_key=$SECRECT_KEY;///这个就是个API密码。MD5 32位。
        $data=array_filter($data);
        ksort($data);
        $str='';
        foreach($data as $k=>$v) {
        $str.=$k.'='.$v.'&';
        }
        $str.='key='.$secrect_key;
        $data['sign']=md5($str);
        //生成签名算法
        $xml=$this->arraytoxml($data);
        $url='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'; //调用接口
        $res=$this->curl_post_ssl($url,$xml);
        $responseObj=$this->xmltoarray($res);

    //   array (
    //         'return_code' => 'SUCCESS',
    //         'return_msg' => '支付失败',
    //         'mch_appid' => 'wxdedae9ac8da366ad',
    //         'mchid' => '1523166321',
    //         'result_code' => 'FAIL',
    //         'err_code' => 'AMOUNT_LIMIT',
    //         'err_code_des' => '付款金额超出限制。低于最小金额0.30元或累计超过500.00元。',
    //       )

        $rescode= $responseObj["return_code"];
        if($rescode =="SUCCESS"){

            $result_code= $responseObj["result_code"];
            if($result_code =="FAIL"){
                $err_code_des = $responseObj["err_code_des"];
                $err_code = $responseObj["err_code"];
                Log::record(json_encode($responseObj),'emergency');
                return $this->renderError("$err_code - $err_code_des");
            }else{
                $trade_no = $responseObj["partner_trade_no"];
                $payment_no = $responseObj["payment_no"];
    
                $session = $this->request->session();
                $user = $session['user']; 
                $time =date('Y-m-d H:i:s',time());
    
                Db::table('refund')->where('id',$refund['id'])->update([ 'status'=> 0, 'update_at' => $time, 'update_at' => $time,'update_user_id'=>$user["id"],'payment_no'=>$payment_no]);

                return $this->renderSuccess(1);
            }
 
        }

        return $this->renderError('未知错误');

    }
    
    /**
 * [xmltoarray xml格式转换为数组]
 * @param [type] $xml [xml]
 * @return [type]  [xml 转化为array]
 */
public function xmltoarray($xml) { 
    //禁止引用外部xml实体 
    libxml_disable_entity_loader(true); 
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
    $val = json_decode(json_encode($xmlstring),true); 
    return $val;
   }
  
   /**
   * [arraytoxml 将数组转换成xml格式（简单方法）:]
   * @param [type] $data [数组]
   * @return [type]  [array 转 xml]
   */
   function arraytoxml($data){
    $str='<xml>';
    foreach($data as $k=>$v) {
     $str.='<'.$k.'>'.$v.'</'.$k.'>';
    }
    $str.='</xml>';
    return $str;
   }
  
   /**
   * [createNoncestr 生成随机字符串]
   * @param integer $length [长度]
   * @return [type]   [字母大小写加数字]
   */
  public  function createNoncestr($length =32){
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789"; 
    $str ="";
  
    for($i=0;$i<$length;$i++){ 
     $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1); 
    } 
    return $str;
   }
  
   /**
   * [curl_post_ssl 发送curl_post数据]
   * @param [type] $url  [发送地址]
   * @param [type] $xmldata [发送文件格式]
   * @param [type] $second [设置执行最长秒数]
   * @param [type] $aHeader [设置头部]
   * @return [type]   [description]
   */
  public  function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array()){
    $isdir = $_SERVER['DOCUMENT_ROOT']."/cert/";//证书位置;绝对路径

    $ch = curl_init();//初始化curl
  
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置执行最长秒数
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
    curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//证书类型
    curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//证书位置
    curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中规定的私钥的加密类型
    curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//证书位置
    //curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
    //curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
    if (count($aHeader) >= 1) {
     curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//设置头部
    }
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);//全部数据使用HTTP协议中的"POST"操作来发送
  
    $data = curl_exec($ch);//执行回话
    if ($data) {
     curl_close($ch);
     return $data;
    } else {
     $error = curl_errno($ch);
     Log::record("curl_post_ssl call faild, errorCode:$error",'emergency');
     curl_close($ch);
     return false;
    }
   }
}